package com.itogis.interceptors.autoWebEvent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.itogis.interceptors.autoWebEvent.WebStatisticsServlet2;

public class AbstractSpringContextServlet extends HttpServlet {
	private static final long serialVersionUID = 8907626450163952267L;
	protected static final String DEFAULT_CHARSET = "UTF-8";
	private static final int BUF_SIZE = 512;

	protected Logger log = Logger.getLogger(AbstractSpringContextServlet.class);

	protected Document parseRequestXml(HttpServletRequest req) throws Exception {
		try {
			return new SAXReader()
					.read(new BufferedReader(new InputStreamReader(req
							.getInputStream(), DEFAULT_CHARSET), BUF_SIZE));
		} catch (UnsupportedEncodingException e) {
			log.error("请求消息的字符集不是 " + DEFAULT_CHARSET);
			throw new Exception("读取请求消息内容失败：请求消息内容的字符集不是" + DEFAULT_CHARSET
					+ "，" + e.getMessage());
		} catch (IOException e) {
			log.error("读取请求消息的内容IO失败", e);
			throw new Exception("读取请求消息内容IO失败：" + e.getMessage());
		} catch (DocumentException e) {
			log.error("解析XML请求消息内容失败", e);
			throw new Exception("解析XML请求消息内容失败：" + e.getMessage());
		}
	}

	protected ApplicationContext getApplicationContext() {
		ServletContext sc = this.getServletConfig().getServletContext();
		return WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
	}

	// protected SpStatisticsService2 getSpStatisticsService() {
	// return this.getSpringBean(SpStatisticsService2.class);
	// }
	//
	// protected CommonServiceRemote getCommonService() {
	// return this.getSpringBean(CommonServiceRemote.class);
	// }
	//
	// protected UserServiceRemote getUserService() {
	// return this.getSpringBean(UserServiceRemote.class);
	// }
	//
	// protected UserToken parseUserToken(HttpServletRequest request)
	// throws ApplicationException {
	// return CommonServiceBasedUtil.parseUserTokenFromCookie(request, this
	// .getCommonService());
	// }

	public static String parseUserTokenFromCookie(
			HttpServletRequest request)
			throws Exception {
		Cookie[] cookies = request.getCookies();
		String userTokenValue = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("UserToken.COOKIE_NAME".equals(cookie.getName())) {
					userTokenValue = cookie.getValue();
					break;
				}
			}
		}
		
		return "";
	}

	public static void writeUserTokenToCookie(HttpServletResponse response)
			throws Exception {

		StringBuilder userTokenValueBuilder = new StringBuilder();
		userTokenValueBuilder.append("UserToken:");
		userTokenValueBuilder.append("");
		userTokenValueBuilder.append(":");
		String secretValue = "";
		userTokenValueBuilder.append("");
		String userTokenValue = userTokenValueBuilder.toString();
		Cookie cookie = new Cookie("UserToken.COOKIE_NAME", userTokenValue);
		cookie.setDomain("UserToken.COOKIE_DOMAIN");
		cookie.setPath("UserToken.COOKIE_PATH");
		response.addCookie(cookie);
	}
	
	protected <T> T getSpringBean(Class<T> beanClass) {
		Map beans = this.getApplicationContext().getBeansOfType(beanClass);
		return (T) beans.values().iterator().next();
	}
}
